/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * Author: cuandm
 * Date: Apr 22, 2011 3:40:09 PM
 */
package com.memcached;

import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.memcached.utils.MemcachedConfigInfo;

/**
 * @description: Memcached包装类，client端调用
 * @author:
 * 
 */
public class Memcached {

	// 创建全局的唯一实例
	protected static MemCachedClient memCachedClient = new MemCachedClient();

	protected static Memcached memcached = new Memcached();

	protected Memcached() {
	}

	// 获取Memcached实例
	public static Memcached getInstance() {
		return memcached;
	}

	/**
	 * 设置与缓存服务器的连接池
	 */
	static {
		// 获取socke连接池的实例对象
		SockIOPool pool = SockIOPool.getInstance();

		// 设置服务器信息
		pool.setServers(MemcachedConfigInfo.getServers());

		// 服务器其权重
		pool.setWeights(MemcachedConfigInfo.getWeights());

		// 设置初始连接数、最小和最大连接数以及最大处理时间
		pool.setInitConn(MemcachedConfigInfo.getInitConn());
		pool.setMinConn(MemcachedConfigInfo.getMinConn());
		pool.setMaxConn(MemcachedConfigInfo.getMaxConn());
		pool.setMaxIdle(MemcachedConfigInfo.getMaxIdle());

		// 设置主线程的睡眠时间
		pool.setMaintSleep(MemcachedConfigInfo.getMaintSleep());

		// 设置TCP的参数，连接超时等
		pool.setNagle(MemcachedConfigInfo.getNagle());
		pool.setSocketTO(MemcachedConfigInfo.getSocketTO());
		pool.setSocketConnectTO(MemcachedConfigInfo.getSocketConnectTO());

		// 初始化连接池
		pool.initialize();

		// 压缩设置，超过指定大小（单位为K）的数据都会被压缩
		memCachedClient.setCompressEnable(MemcachedConfigInfo.getCompressEnable());
		memCachedClient.setCompressThreshold(MemcachedConfigInfo.getCompressThreshold());
	}

	/**
	 * 添加一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @return
	 */

	public boolean add(String key, Object value) {
		return memCachedClient.add(key, value);
	}

	public boolean add(String key, Object value, Date expiry) {
		return memCachedClient.add(key, value, expiry);
	}

	public boolean replace(String key, Object value) {
		return memCachedClient.replace(key, value);
	}

	public boolean replace(String key, Object value, Date expiry) {
		return memCachedClient.replace(key, value, expiry);
	}

	public boolean delete(String key) {
		return memCachedClient.delete(key);
	}

	public boolean delete(String key, Date expiry) {
		return memCachedClient.delete(key, expiry);
	}

	/**
	 * 根据指定的关键字获取对象.
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		return memCachedClient.get(key);
	}

}
